<template>
    <div>
        <el-image-viewer v-if="viewerVisible" 
            :url-list="HignSpeedUrls"
            :initial-index="imgcurrentIndex" 
            @close="closeViewerimg" />
        <!-- <el-button v-if="isopenCameraBtn"  type="primary" @click="CameraBtn" class='mb-3'>
            启动摄像头
        </el-button>
        <el-button v-else type="danger" @click="CloseCameraBtn" class='mb-3'>
            关闭摄像头
        </el-button> -->
        <el-button   type="primary" @click="CameraBtn" class='mb-3'>
            启动摄像头
        </el-button>
        <el-button  type="danger" @click="CloseCameraBtn" class='mb-3'>
            关闭摄像头
        </el-button>
        <el-row style="width: 100%;">
            <el-col :span="22">
                <div style="width: 422px;height: 302px;border: 1px solid #666666; background: #fff">
                    <canvas ref="videoCanvas" width="420" height="300"></canvas>
                </div>
            </el-col>
        </el-row>
        <el-row style="width: 100%;" class="mt-3">
            <el-col :span="24" >
                <el-button type="primary" @click="SaveCameraBtn" class='mb-3'>
                    保存
                </el-button>
            </el-col>
            <el-col :span="24" style="display: flex;flex-wrap: wrap;gap: 10px;">
                <div class="block" style="width: 110px; height: 110px;position: relative;margin-right: 10px;"
                    v-for="(img, index) in HignSpeedUrls"  @click="clickImage(index)"
                    :key="index">
                  <el-image style="width: 110px; height: 110px;position: relative;"
                    :src="img"
                    fit="contain" 
                    >
                      <template #error>
                          <div class="image-slot">
                              请使用高拍仪
                          </div>
                      </template>
                  </el-image>
                  <el-icon class="me-1 edit-icon" @click="deletHighSpeedImg(index, $event)">
                      <circle-close />
                  </el-icon>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { getCurrentInstance, onMounted, ref } from "vue";
import { ElMessageBox } from 'element-plus'
const { proxy } = getCurrentInstance()
import { getPoliceAreaInfo } from "@/api/PoliceAreaManage/PoliceAreaManage";
import { WebSocketService } from "@/utils/websocket";  // 导入 WebSocket 服务
import {SignuploadFile,SignDelFile,SignList,SignimageInfo,saveUploadFile} from "@/api/ApplyDetail/ApplyDetail";
import {ApplyDetailInfo} from "@/api/ApplyDetail/ApplyDetail";
const ishow = ref(false)
const isHighSpeedValue = ref()
const HignSpeedUrls = ref([])
const HignSpeedSubUploadID = ref([])
const imgcurrentIndex = ref(0);
const viewerVisible = ref(false)
const imgurl = ref();

const isopenCameraBtn = ref(true) // 摄像头按钮是否显示

// 新增帧率控制相关变量
const targetFPS = 20; // 目标帧率(可根据需要调整)1秒15帧。可以调整，越高越流畅，但是对内存及  Gpu要求越高
const frameInterval = 1000 / targetFPS; // 每帧间隔(ms)
let lastRenderTime = 0; // 上次渲染时间戳
let frameQueue = []; // 帧队列(最多保留1帧)
let isRendering = false; // 是否正在渲染中
let animationFrameId = null; // requestAnimationFrame ID


const videoCanvas = ref(null); // Canvas DOM 引用
const canvasCtx = ref(null);   // Canvas 2D 上下文
const form = ref(); // 表单引用
const props = defineProps({
  data: {
    type: Object,
    required: true, // 如果这个属性是必需的
  },
})
// WebSocket 服务实例
let webSocketService = null;
onMounted(() => {
    nextTick(() => {
    if (videoCanvas.value) {
      canvasCtx.value = videoCanvas.value.getContext('2d');
      videoCanvas.value.width = '420';
      videoCanvas.value.height = '300';
      // console.log("Canvas初始化完成，尺寸:", videoCanvas.value.width, "x", videoCanvas.value.height);
    } else {
      console.error("Canvas元素未找到！");
    }
  });
  if (props.data && props.data.jw_applydetail_id) {
    // 调用接口获取详细数据
    getApplyDetailInfo(props.data.jw_applydetail_id)

    }
    getPoliceAreaInfos(props.data)
   
})
// 获取详情
const getApplyDetailInfo = async () => {
await ApplyDetailInfo(props.data.jw_applydetail_id).then(res => {
    form.value = res.data
})
}

// 获取办案区ip地址
const getPoliceAreaInfos = async (querydata) => {
  // console.log(querydata,'这里执行了取办案区ip地址，querydata是从列表过来的数据')
  // 这里执行了取办案区ip地址，querydata是从列表过来的数据
    // 我想在这里添加一个，输出当前地址栏路径

getPoliceAreaInfo(querydata.policearea_id).then(res => {
  // webSocketService = new WebSocketService(websocketUrl.value);
    webSocketService = new WebSocketService('ws://192.168.3.34:18887');
     // 启动 WebSocket 连接
    webSocketService.createWebSocket()
      .then(() => {
        const path = window.location.pathname
        const istrue =  path.includes('/PoliceWork/')
        if(istrue){
            ElMessage.success({
            message: '与终端设备连接成功--测试那里',
            showClose: true,
        })
        }
      })
      .catch((error) => {
        // ElMessage.error({
        //   message: '与终端连接失败',
        //   showClose: true,
        // })
      });
    // 设置接收到消息时的回调
    webSocketService.setOnMessageCallback(handleWebSocketMessage);
})
}


// 点击关闭摄像头{
function CloseCameraBtn() {
  webSocketService.sendMessage('closeCamera')
  isopenCameraBtn.value = true // 摄像头按钮是否显示
  // 清空画布
  clearCanvas();
}
// 清空画布的函数
function clearCanvas() {
  if (canvasCtx.value && videoCanvas.value) {
    console.log("清空画布")
    // 清除整个画布
    // 强制重绘（备用方案）
  setTimeout(() => {
    if (canvasCtx.value) {
      canvasCtx.value.clearRect(0, 0, 
        videoCanvas.value.width, 
        videoCanvas.value.height);
    }
    // 可选：填充白色背景（如果需要）
      canvasCtx.value.fillStyle = '#ffffff';
      canvasCtx.value.fillRect(0, 0, videoCanvas.value.width, videoCanvas.value.height);
  }, 500);
  }
}
// 点击启动摄像头
function CameraBtn() {
    isHighSpeedValue.value = 2       //1是签名，2是高拍仪，3是身份证
    if(webSocketService){
      SendMes()
      isopenCameraBtn.value = false // 摄像头按钮是否显示
    }else{
      // 创建 WebSocket 实例
      webSocketService = new WebSocketService(websocketUrl.value);
      // webSocketService = new WebSocketService('ws://192.168.3.34:18887');
      // 启动 WebSocket 连接
      webSocketService.createWebSocket()
        .then(() => {
          ElMessage.success({
            message: '与终端设备连接成功-点击摄像头',
            showClose: true,
          })
        })
        .catch((error) => {
          // proxy.$modal.error(`WebSocket 连接失败: ${error.message}`);
        });

      // 设置接收到消息时的回调
      webSocketService.setOnMessageCallback(handleWebSocketMessage);
      // 发送消息
      SendMes()
      isopenCameraBtn.value = false // 摄像头按钮是否显示
    }
    
}
// 发送消息
function SendMes() {
  webSocketService.sendMessage(isHighSpeedValue.value)        //1是签名，2是高拍仪，3是身份证
}
// 点击保存图片
async function SaveCameraBtn() {
  webSocketService.sendMessage(11)
    // try {
    //     // 1. 检查Canvas是否可用
    //     if (!videoCanvas.value) {
    //         ElMessage.error('Canvas未初始化');
    //         return;
    //     }
    //     // 2. 将Canvas转换为Blob对象
    //     const blob = await new Promise((resolve) => {
    //         videoCanvas.value.toBlob((blob) => {
    //             resolve(blob);
    //         }, 'image/jpeg', 1); // 质量参数0.9（90%质量）
    //     });

    //     if (!blob) {
    //         ElMessage.error('无法生成图片');
    //         return;
    //     }
    //     // 3. 生成预览URL并保存到列表
    //     const previewUrl = URL.createObjectURL(blob);
    //     HignSpeedUrls.value.push(previewUrl);
    //     // 我需要在这里保存一下图片，显示在HignSpeedUrls中
    //     // 3. 准备上传参数
    //     const query = {
    //         jwApplyDetailId:form.value.jwApplydetailId,
    //         md5key: '12313', // 根据实际情况修改
    //         fileType: '2'    // 2人员进入高拍仪 3体检高拍仪 4体检医生签名 5体检涉案人签名
    //     };

    //     // 4. 创建FormData
    //     const formData = new FormData();
    //     formData.append('file', blob, 'capture.jpg'); // 使用有意义的文件名
        
    //     // 6. 调用接口进行上传
    //     SignuploadFile(formData, query).then(res => {
    //         proxy.$modal.msgSuccess(`照片上传成功`)
    //         HignSpeedSubUploadID.value.push(res.msg);
    //     })
    // } catch (error) {
    //     console.error('保存图片失败:', error);
    //     ElMessage.error('保存图片失败: ' + error.message);
    // }
}

// 处理 WebSocket 二进制消息
// 修改后的handleWebSocketMessage函数
function handleWebSocketMessage(message) {
    if (message === 'cancel' || message === 'end') {
        proxy.$modal.msgWarning(`用户${message === 'cancel' ? '取消' : '结束'}了操作`);
        return;
    }
    // try {
    //     // 解析JSON消息
    //     const data = typeof message === 'string' ? JSON.parse(message) : message;
        
    //     // 检查是否有photo字段
    //     if (data.photo) {
    //         // 创建Base64图片URL
    //         const imgUrl = `data:image/jpeg;base64,${data.photo}`;
            
    //         // 将图片URL添加到HignSpeedUrls数组
    //         HignSpeedUrls.value.push(imgUrl);


    //         // 2. 转成 Blob（base64 => binary）
    //         const byteString = atob(data.photo);
    //         const arrayBuffer = new ArrayBuffer(byteString.length);
    //         const uint8Array = new Uint8Array(arrayBuffer);
    //         for (let i = 0; i < byteString.length; i++) {
    //             uint8Array[i] = byteString.charCodeAt(i);
    //         }
    //         const blob = new Blob([uint8Array], { type: 'image/jpeg' });

    //         // 3. 准备上传参数
    //         const query = {
    //             jwApplyDetailId: form.value.jwApplydetailId,
    //             md5key: '12313',
    //             fileType: '2' // 2人员进入高拍仪
    //         };

    //         const formData = new FormData();
    //         formData.append('file', blob, 'capture.jpg');

    //         // 4. 调用上传接口
    //         SignuploadFile(formData, query).then(res => {
    //             proxy.$modal.msgSuccess(`照片上传成功`);
    //             HignSpeedSubUploadID.value.push(res.msg);
    //         });
    //     }
    // } catch (error) {
    //     console.error('处理WebSocket消息出错:', error);
    // }

    ////////保存图片结束//////////////保存图片结束////////////////////////////////////保存图片结束
    if (!(message instanceof Blob)) {
        console.warn("未知消息格式:", message);
        return;
    }

    // 将Blob存入帧队列(最多保留最新的一帧)
    if (frameQueue.length > 0) {
        frameQueue[0] = message; // 替换旧帧
    } else {
        frameQueue.push(message);
    }

    // 触发渲染流程
    scheduleRender();
}

// 新增的调度渲染函数
function scheduleRender() {
    // 如果已经在渲染或队列为空，则跳过
    if (isRendering || frameQueue.length === 0) return;
    
    const now = performance.now();
    const elapsed = now - lastRenderTime;
    
    // 如果还没到下一帧的渲染时间，延迟执行
    if (elapsed < frameInterval) {
        if (animationFrameId) {
            cancelAnimationFrame(animationFrameId);
        }
        animationFrameId = requestAnimationFrame(() => {
            scheduleRender();
        });
        return;
    }
    
    // 执行渲染
    processRender();
}

// 新增的处理渲染函数
function processRender() {
    if (isRendering || frameQueue.length === 0) return;
    
    isRendering = true;
    const blob = frameQueue.shift();
    lastRenderTime = performance.now();
    
    // 使用Blob创建对象URL
    const url = URL.createObjectURL(blob);
    const img = new Image();
    
    img.onload = () => {
        if (canvasCtx.value) {
            canvasCtx.value.clearRect(0, 0, videoCanvas.value.width, videoCanvas.value.height);
            canvasCtx.value.drawImage(
                img, 
                0, 0, 
                videoCanvas.value.width, 
                videoCanvas.value.height
            );
        }
        
        // 清理资源
        URL.revokeObjectURL(url);
        isRendering = false;
        
        // 检查是否有新帧需要处理
        if (frameQueue.length > 0) {
            scheduleRender();
        }
    };
    
    img.onerror = (e) => {
        console.error("图片加载失败:", e);
        URL.revokeObjectURL(url);
        isRendering = false;
        
        // 即使出错也继续处理下一帧
        if (frameQueue.length > 0) {
            scheduleRender();
        }
    };
    
    img.src = url;
}


// 组件卸载时清理资源
onUnmounted(() => {
    if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
    }
    
    // 清空帧队列
    frameQueue = [];
    
    // 关闭WebSocket连接
    if (webSocketService) {
        webSocketService.close();
    }
});

// 用于关闭预览
const clickImage = (index) => {
  imgcurrentIndex.value = index
    setTimeout(() => {
        viewerVisible.value = true;
    }, 100);
};
// 用于关闭预览
const closeViewerimg = () => {
  viewerVisible.value = false;
};
// 删除图片
const deletHighSpeedImg = async (index, event) => {
  event.stopPropagation();
  console.log(HignSpeedSubUploadID.value[index])
  await SignDelFile(HignSpeedSubUploadID.value[index]).then(res => {
      HignSpeedUrls.value.splice(index, 1);
      HignSpeedSubUploadID.value.splice(index, 1);
      proxy.$modal.msgSuccess(`删除成功`)
  })
}
// 关闭后的回调事件
const handleClick = () => {

}
</script>